package com.example.archive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.archive.entity.Archive;
import com.example.archive.entity.ArchiveApprovalRequest;
import com.example.archive.entity.User;
import com.example.archive.mapper.ArchiveApprovalRequestMapper;
import com.example.archive.mapper.UserMapper;
import com.example.archive.mapper.ArchiveMapper;
import com.example.archive.service.ArchiveApprovalRequestService;
import com.example.archive.service.ArchiveService;
import com.example.archive.util.PageParam;
import com.example.archive.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ArchiveApprovalRequestServiceImpl implements ArchiveApprovalRequestService {

    @Autowired
    private ArchiveApprovalRequestMapper requestMapper;

    @Autowired
    private ArchiveService archiveService;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private ArchiveMapper archiveMapper;

    @Override
    public Result<Boolean> submitRequest(ArchiveApprovalRequest request) {
        request.setRequestTime(new Date());
        request.setStatus("pending"); // Default status
        int insert = requestMapper.insert(request);
        return insert > 0 ? Result.success(true) : Result.fail(500, "提交请求失败");
    }

    @Override
    public Result<IPage<ArchiveApprovalRequest>> listRequests(PageParam pageParam, String status, Integer requesterId, Integer approverId) {
        Page<ArchiveApprovalRequest> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        QueryWrapper<ArchiveApprovalRequest> queryWrapper = new QueryWrapper<>();

        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }
        if (requesterId != null) {
            queryWrapper.eq("requester_id", requesterId);
        }
        if (approverId != null) {
            queryWrapper.eq("approver_id", approverId);
        }
        if (pageParam.getSearch() != null && !pageParam.getSearch().isEmpty()) {
            queryWrapper.and(wrapper -> wrapper.like("request_type", pageParam.getSearch())
                                               .or().like("notes", pageParam.getSearch()));
        }

        IPage<ArchiveApprovalRequest> requestIPage = requestMapper.selectPage(page, queryWrapper);
        
        // 翻译ID为名称
        List<ArchiveApprovalRequest> records = requestIPage.getRecords();
        for (ArchiveApprovalRequest request : records) {
            // 翻译档案ID为档案标题
            if (request.getArchiveId() != null) {
                Archive archive = archiveMapper.selectById(request.getArchiveId());
                if (archive != null) {
                    request.setArchiveTitle(archive.getTitle());
                }
            }
            
            // 翻译申请人ID为申请人姓名
            if (request.getRequesterId() != null) {
                User requester = userMapper.selectById(request.getRequesterId());
                if (requester != null) {
                    request.setRequesterName(requester.getName() != null ? requester.getName() : requester.getUsername());
                }
            }
            
            // 翻译审批人ID为审批人姓名
            if (request.getApproverId() != null) {
                User approver = userMapper.selectById(request.getApproverId());
                if (approver != null) {
                    request.setApproverName(approver.getName() != null ? approver.getName() : approver.getUsername());
                }
            }
        }
        
        return Result.success(requestIPage);
    }

    @Override
    public Result<Boolean> approveRequest(Integer requestId, Integer approverId, String notes) {
        ArchiveApprovalRequest request = requestMapper.selectById(requestId);
        if (request == null) {
            return Result.fail(404, "请求未找到");
        }
        if (!"pending".equals(request.getStatus())) {
            return Result.fail(400, "请求已处理");
        }

        // Update archive based on request type
        if ("confidentiality_level_adjustment".equals(request.getRequestType())) {
            Archive archive = new Archive();
            archive.setArchiveId(request.getArchiveId());
            archive.setSecurityLevel(request.getRequestedValue());
            archive.setLastModifiedBy(approverId);
            archive.setUpdatedAt(new Date());
            Result<Boolean> updateResult = archiveService.updateArchive(archive);
            if (!updateResult.getData()) {
                return Result.fail(500, "更新档案失败");
            }
        } else {
            // Handle other request types like paper_archive_retrieval, modification etc.
            // For now, simply approve the request.
        }

        request.setStatus("approved");
        request.setApproverId(approverId);
        request.setApprovalTime(new Date());
        request.setNotes(notes);
        int update = requestMapper.updateById(request);
        return update > 0 ? Result.success(true) : Result.fail(500, "批准请求失败");
    }

    @Override
    public Result<Boolean> rejectRequest(Integer requestId, Integer approverId, String notes) {
        ArchiveApprovalRequest request = requestMapper.selectById(requestId);
        if (request == null) {
            return Result.fail(404, "请求未找到");
        }
        if (!"pending".equals(request.getStatus())) {
            return Result.fail(400, "请求已处理");
        }

        request.setStatus("rejected");
        request.setApproverId(approverId);
        request.setApprovalTime(new Date());
        request.setNotes(notes);
        int update = requestMapper.updateById(request);
        return update > 0 ? Result.success(true) : Result.fail(500, "拒绝请求失败");
    }

    @Override
    public Result<ArchiveApprovalRequest> getRequestById(Integer requestId) {
        ArchiveApprovalRequest request = requestMapper.selectById(requestId);
        if (request == null) {
            return Result.fail(404, "请求未找到");
        }
        
        // 翻译ID为名称
        if (request.getArchiveId() != null) {
            Archive archive = archiveMapper.selectById(request.getArchiveId());
            if (archive != null) {
                request.setArchiveTitle(archive.getTitle());
            }
        }
        
        if (request.getRequesterId() != null) {
            User requester = userMapper.selectById(request.getRequesterId());
            if (requester != null) {
                request.setRequesterName(requester.getName() != null ? requester.getName() : requester.getUsername());
            }
        }
        
        if (request.getApproverId() != null) {
            User approver = userMapper.selectById(request.getApproverId());
            if (approver != null) {
                request.setApproverName(approver.getName() != null ? approver.getName() : approver.getUsername());
            }
        }
        
        return Result.success(request);
    }
} 